<template>
  <div>
    <div v-show="false">
      <table ref="tabs" id="tabs" border="1" style="font-size: 18px;border-collapse: collapse;">
        <tr>
          <th style="border:1px solid #000000;" v-for="(item, index) in header" :key="index">{{ item.label }}</th>
        </tr>
        <tr v-for="(item, index) in data" :key="index">
          <td style="border:1px solid #000000;padding: 10px 20px;">{{ item.err }}</td>
          <td style="border:1px solid #000000;padding: 10px 20px;">{{ isNaN(item.fill) ? item.fill : "'" + item.fill }}</td>
        </tr>
      </table>
    </div>
    <a ref="link" class="download-btn button-n" v-on:click="tabClick">下载问题列表</a>
  </div>
</template>
<script type="text/ecmascript-6">
export default {
  name: 'component_name',
  data () {
    return {
    }
  },
  props: {
    header: {
      type: Array,
      default: function () {
        return [
          {
            label: '匹配情况',
            prop: 'err'
          }, {
            label: '填入项',
            prop: 'fill'
          }
        ]
      }
    },
    data: {
      type: Array,
      default: function () {
        return [
          // {
          //   err: '123',
          //   fill: '963'
          // }, {
          //   err: '999',
          //   fill: '888'
          // }, {
          //   err: '',
          //   fill: '963'
          // }
        ]
      }
    },
    fileName: {
      type: String,
      default: '未匹配对照表.xls'
    }
  },
  computed: {
    headerLabel: function () {
      let result
      result = this.header.map((item) => {
        return item.label
      })
      result = result.join(',')
      return result
    },
    headerProp: function () {
      let result
      result = this.header.map((item) => {
        return item.prop
      })
      return result
    }
  },
  methods: {
    handleClick () {
      var csvContent = 'data:text/csv;charset=utf-8,\ufeff'
      csvContent += this.headerLabel + '\n'
      this.data.forEach((item, index) => {
        let dataString = ''
        for (let i = 0; i < this.headerProp.length; i++) {
          dataString += item[this.headerProp[i]] + ','
        }
        csvContent += index < this.data.length ? dataString.replace(/,$/, '\n') : dataString.replace(/,$/, '')
      })
      this.$refs.link.setAttribute('href', encodeURI(csvContent))
      this.$refs.link.setAttribute('download', this.fileName)
      this.$emit('downed')
    },
    tabClick () {
      let tabs = this.$refs.tabs.outerHTML
      let html = `<html><head><meta charset='utf-8' /></head><body>${tabs}</body></html>`
      let excelBlob = new Blob([html], { type: 'application/vnd.ms-excel' })
      this.$refs.link.setAttribute('href', URL.createObjectURL(excelBlob))
      this.$refs.link.setAttribute('download', this.fileName)
      this.$emit('downed')
    }
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
.button-n
  text-decoration none
</style>
